package com.lagou.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lagou.entity.CourseComment;
import com.lagou.service.CourseCommentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("course")
public class CourseCommentController {
    @Reference
    private CourseCommentService courseCommentService;

    @GetMapping("comment/saveCourseComment")
    public Object saveCourseComment(Integer courseId, Integer userId, String userName, String comment) {
        CourseComment courseComment = new CourseComment();
        userName = new String(userName.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        comment = new String(comment.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        courseComment.setCourseId(courseId); //课程编号
        courseComment.setSectionId(0); //章节编号 (预留字段)
        courseComment.setLessonId(0); //课时编号 (预留字段)
        courseComment.setUserId(userId); //用户编号
        courseComment.setUserName(userName); //用户昵称
        courseComment.setParentId(0); //没有父id (预留字段)
        courseComment.setComment(comment); //留言内容
        courseComment.setType(0); //0用户留言 (预留字段)
        courseComment.setLastOperator(userId); //(预留字段)

        return courseCommentService.saveComment(courseComment);
    }

    @GetMapping("comment/getCourseCommentList/{courseId}/{pageIndex}/{pageSize}")
    public List<CourseComment> getCommentsByCourseId(@PathVariable Integer courseId, @PathVariable Integer pageIndex,
                                                     @PathVariable Integer pageSize) {
        Integer offset = Math.max((pageIndex - 1), 0) * pageSize;

        return courseCommentService.getCommentsByCourseId(courseId, offset, pageSize);
    }

    @GetMapping("comment/saveFavorite/{commentId}/{userId}")
    public Integer saveFavorite(@PathVariable Integer commentId, @PathVariable Integer userId){
        return courseCommentService.saveFavorite(commentId, userId);
    }

    @GetMapping("comment/cancelFavorite/{commentId}/{userId}")
    public Integer cancelFavorite(@PathVariable Integer commentId, @PathVariable Integer userId) {
        return courseCommentService.cancelFavorite(commentId, userId);
    }
}
